package system_configuration_dao

import (
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/interface/dao"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
)

func (cls *SystemConfiguration) SafeTakeAllConfiguration(ctx context.Context, options ...dao.SystemConfigurationOption) ([]*model.SystemConfiguration, errors.Error) {
	// 检查数据表是否存在
	if !cls.GetDb(ctx).Migrator().HasTable(&model.SystemConfiguration{}) {
		return nil, nil
	}

	var session = cls.GetDb(ctx).Model(new(model.SystemConfiguration))

	var metadata = dao.NewMetadata()
	for _, o := range options {
		var err errors.Error
		session, err = o(session, metadata)
		if nil != err {
			if err.IsType(errors.ErrorTypeRecordNotFound) {
				return nil, nil
			}

			return nil, err.Relation(errors.ErrorServerInternalError("IDC_ON.C_ON.STAC_ON.285118", "配置选项失败"))
		}
	}

	// 获取所有配置
	var configurations []*model.SystemConfiguration
	if err := session.Find(&configurations).Error; err != nil {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("IDC_ON.C_ON.STAC_ON.273256 查询数据失败: %v", err)

		return nil, errors.New(errors.ErrorTypeServerInternalError, "IDC_ON.C_ON.STAC_ON.225212", "查询数据失败")
	}

	return configurations, nil
}
